package com.zjb.demo.system.controller;

import cn.hutool.core.util.ArrayUtil;
import com.mybatisflex.core.paginate.Page;
import com.zjb.demo.common.constant.SecurityConstants;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.common.domain.response.TreeSelect;
import com.zjb.demo.common.util.RSAUtils;
import com.zjb.demo.common.util.SecurityUtils;
import com.zjb.demo.system.domain.SysDept;
import com.zjb.demo.system.domain.User;
import com.zjb.demo.system.domain.query.UserQuery;
import com.zjb.demo.system.service.SysDeptService;
import com.zjb.demo.system.service.SysPostService;
import com.zjb.demo.system.service.SysRoleService;
import com.zjb.demo.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.noear.solon.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author 庄佳彬
 * @since 2023/12/22 11:24
 */
@Controller
@Mapping("/system/user")
@Api(tags = "系统：用户管理")
public class UserController {

    @Inject
    private UserService userService;
    @Inject
    private SysRoleService roleService;
    @Inject
    private SysDeptService deptService;
    @Inject
    private SysPostService postService;

    @Get
    @Mapping("/list")
    @ApiOperation(value = "分页查询用户")
    public AjaxResult<Page<User>> list(UserQuery query) {
        return AjaxResult.success(userService.pageList(query));

    }

    @Get
    @Mapping("/{id}")
    @ApiOperation(value = "根据ID查询用户")
    public AjaxResult<User> getById(long id) {
        return AjaxResult.success(userService.getById(id));
    }

    @Get
    @Mapping("/deptTree")
    @ApiOperation(value = "部门树")
    public AjaxResult<List<TreeSelect>> deptTree(SysDept sysDept) {
        return AjaxResult.success(deptService.selectDeptTreeList(sysDept));
    }

    @Post
    @Mapping
    @ApiOperation(value = "保存用户")
    public AjaxResult<Boolean> save(User user) {
        if (userService.checkUserNameUnique(user)) {
            return AjaxResult.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (userService.existsByEmail(user.getEmail())) {
            return AjaxResult.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (userService.existsByPhone(user.getPhoneNumber())) {
            return AjaxResult.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        var password = RSAUtils.decrypt(user.getPassword(), SecurityConstants.PRIVATE_KEY);
        user.setPassword(password);
        return AjaxResult.success(userService.saveUser(user));
    }

    @Put
    @Mapping
    @ApiOperation(value = "修改用户")
    public AjaxResult<Boolean> update(@Body User user) {
        if (userService.checkUserNameUnique(user)) {
            return AjaxResult.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (userService.existsByEmail(user.getEmail())) {
            return AjaxResult.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (userService.existsByPhone(user.getPhoneNumber())) {
            return AjaxResult.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        return AjaxResult.success(userService.updateUser(user));
    }

    @Delete
    @Mapping("/{userIds}")
    @ApiOperation(value = "删除用户")
    public AjaxResult<Boolean> delete(Long[] id) {
        var currentUserid = SecurityUtils.getUserId();
        if (ArrayUtil.contains(id, currentUserid)) {
            return AjaxResult.fail("当前用户不能删除");
        }
        return AjaxResult.success(userService.removeUserByIds(List.of(id)));
    }

    @Put
    @Mapping("/resetPwd")
    @ApiOperation(value = "重置密码")
    public AjaxResult<Boolean> resetPwd(@Body User user) {
        var pwd = SecurityUtils.encryptPassword(user.getPassword());
        return AjaxResult.success(userService.resetUserPwd(user.getUserName(), pwd));
    }

    @Put
    @Mapping("/updateAvatar")
    @ApiOperation(value = "修改头像")
    public AjaxResult<Boolean> updateAvatar(@Body User user) {
        return AjaxResult.success(userService.updateAvatar(user.getUserName(), user.getAvatar()));
    }

    @Put
    @Mapping("/changeStatus")
    @ApiOperation(value = "修改用户状态")
    public AjaxResult<Boolean> changeStatus(@Body User user) {
        var updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setStatus(user.getStatus());
        return AjaxResult.success(userService.updateUser(updateUser));
    }

    @Get
    @Mapping("/authRole/{userId}")
    @ApiOperation(value = "根据用户ID查询角色")
    public AjaxResult<Map<String, Object>> authRole(Long userId) {
        var result = new HashMap<String, Object>();
        var user = userService.getById(userId);
        var roles = user.getRoles();
        result.put("roles", SecurityUtils.isAdmin(userId) ? roles : roles.stream().filter(item -> !SecurityUtils.isAdmin(item.getRoleId())).toList());
        result.put("user", user);
        return AjaxResult.success(result);
    }

    @Put
    @Mapping("/authRole")
    @ApiOperation(value = "用户授权角色")
    public AjaxResult<Boolean> authRole(Long userId, Long[] roleIds) {
        return AjaxResult.success(userService.insertUserAuth(userId, roleIds));
    }


}
